<script setup>
import { ref } from 'vue'
import { cityAddService, cityUpdateService } from '@/api/city'
import { Plus } from '@element-plus/icons-vue'
import CitySelect from './CitySelect.vue'

const dialogVisible = ref(false)

const defaultForm = ref({
  elementName: '',
  elementImage: '',
  tagId: '',
  id: null
})
const formModel = ref({
  ...defaultForm.value
})
const formRef = ref(null)
const imgUrl = ref('') // 用于存储图片URL

const open = (row) => {
  dialogVisible.value = true

  if (row.id) {
    imgUrl.value = row.elementImage
    formModel.value.elementImage = row.elementImage
    formModel.value = { ...row }
  } else {
    formModel.value = { ...defaultForm.value }
    imgUrl.value = ''
  }
}
//图片的类型是file 需要再编辑的时候再提交。

const onSelectFile = (uploadFile) => {
  if (uploadFile) {
    imgUrl.value = URL.createObjectURL(uploadFile.raw) // 预览图片
    formModel.value.elementImage = uploadFile.raw
  }
}

const onSubmit = async () => {
  const fd = new FormData()
  fd.append('elementName', formModel.value.elementName)
  fd.append('tagId', formModel.value.tagId)
  if (!formModel.value.elementImage) {
    ElMessage.error('图片不能为空')
    return
  }

  if (
    !formModel.value.elementImage ||
    !(formModel.value.elementImage instanceof File)
  ) {
    ElMessage.error('请选择有效的图片')
    return
  }
  if (formModel.value.elementImage) {
    fd.append('elementImage', formModel.value.elementImage) // 确保这里是文件对象
  }
  // 确保id是有效的，如果不是编辑操作，则不应发送id字段
  const isEdit = formModel.value.id !== undefined && formModel.value.id !== null
  if (isEdit) {
    fd.append('id', parseInt(formModel.value.id))
  }

  console.log('Form data being sent:', Array.from(fd.entries())) // 打印FormData内容
  try {
    let res
    if (isEdit) {
      res = await cityUpdateService(fd)
    } else {
      res = await cityAddService(fd)
    }
    console.log('Operation response:', res)
    if (res && res.code === 401) {
      ElMessage.error(res.message || '操作失败')
    } else {
      ElMessage.success(isEdit ? '编辑成功' : '添加成功')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('Form submission error:', error)
    ElMessage.error('表单提交失败，请检查输入')
  }
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑标签' : '添加标签'"
    width="30%"
  >
    <el-form
      ref="formRef"
      :model="formModel"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="标签名称">
        <el-input
          v-model="formModel.elementName"
          placeholder="请输入标签名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="标签类别">
        <city-select v-model="formModel.tagId"></city-select>
      </el-form-item>
      <el-form-item label="标签图片">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onSelectFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
      // max-width: 100%;
      // max-height: 100%;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
